<template>
    <div id="LoginBox">
        <div class="LoginBox-common">
            <div class="LoginBox-common-text">
                <span>{{ i18n('hello', '您好!') }}</span>
                <span>{{ i18n('welcomeUse', '欢迎使用公司产品') }}</span>
            </div>
            <div class="LoginBox-common-input">
                <image class="LoginBox-common-input-longin" src="@/static/login.png"/>
                <div v-if="isI18nLang=='YES'">
                    <rx-picker v-model="i18nTitle" :rangeList="i18nList" rangeKey="name" @change="change">
                        <div class="login-language-head">
                            <i class="iconfont icon-earth-full" style="margin-right: 5px;font-size: .7rem"></i>{{ i18nTitle }}
                            <i class="iconfont icon-jiantou_liebiaozhankai" style="margin-left: 5px"></i>
                        </div>
                    </rx-picker>
                </div>
                <div class="loginInDiv">
                    <i class="iconfont icon-people"></i>
                    <input type="text" v-model="user.username" :placeholder="i18n('userName','请输入账户名')"/>
                </div>
                <div class="loginInDiv">
                    <i class="iconfont icon-lock"></i>
                    <input type="password" v-model="user.password" confirm-type="search"
                           @confirm="login()" :placeholder="i18n('userPassword','请输入密码')"/>
                </div>
                <div class="loginInDiv" v-if="ignoreValidCode!='true'">
                    <my-icon type="icon-email"></my-icon>
                    <input class="nalcik" type="text" confirm-type="search" @confirm="login()" v-model="user.validCode"
                           :placeholder="i18n('code','验证码')"/>
                    <img :src="imgurl" class='imglist' @click='verification'/>
                </div>
                <button class="btnLogin" @click="login">{{ i18n('loginBtn', '登 录') }}</button>
            </div>
        </div>
    </div>
</template>

<script>
import LoginApi from "@/api/login";
import uuid from '@/common/uuid';
import RxPicker from '@/components/RxPicker'
import common from '@/common/constants.js'
import {loginTypeMap} from '@/common/platformLogin.js';
import TokenUtil from "../../common/TokenUtil";
import md5 from "js-md5";
import {sm2} from 'sm-crypto';
import EncryptUtil from "@/assets/encryptUtil";
import Secret from "../../assets/secret";

export default {
    name: "Login",
    components: {
        RxPicker
    },
    data() {
        return {
            user: {},
            deviceId: '',
            imgurl: '',
            codesrc: null,
            autoBind: true,
            bindVal: true,
            fromUrl: "",
            //是否忽略验证码
            ignoreValidCode: 'true',
            i18nDefault: this._vueAppLanguage,
            i18nTitle: "中文",
            i18nType: "",
            i18nList: [],
            isI18nLang: this._vueAppIsLanguage,
            langShow: false,
            language: uni.getStorageSync("language"),
            tenantId:"",
            instId:"",
            //密码模式
            passwordmode: "default",
            openId:"",
            //国产sm2公钥
            sw2PublicKey:"040E279B33CCEDCAB5AB368BEA4243C7A0AABD0571819855A4C022E554065DCE68A6704974E611C63AA98534864BD1426969A5E8380F879AADD8EF14B595D277D5",
            loading:false,
        }
    },
    created() {
        this.getParamsEncrypt();
        if(this.$route && this.$route.query){
            let item = this.$route.query;
            this.tenantId = item.tenantId;
            this.instId = item.instId;
            this.fromUrl = item.fromUrl;
            this.openId = item.openId;
        }
        if (!this.tenantId) {
            this.tenantId = this.getBaseTenantId();
        }else{
            this.setBaseTenantId(this.tenantId);
        }
        TokenUtil.removeToken();

        this.getMultiLinguals();
        this.getLoginConfig();
        // // 60秒刷新验证码
        this.verification()
        let self_ = this;
        setTimeout(function () {
            self_.verification()
        }, 60000)
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "loginLang", key);
        },
        //获取多语言配置列表
        async getParamsEncrypt(){
            let res = await LoginApi.getParamsEncrypt();
            EncryptUtil.setKeyVal(Secret.key, res.paramsEncrypt || false);
        },
        //获取多语言配置列表
        async getMultiLinguals() {
            let self = this;
            let res = await LoginApi.getMultiLinguals();
            if (res && res.length >= 0) {
                //储存i18列表数据
                this.i18nList = res;
                uni.setStorage({key: "setI18nList", data: res})
            }
            self.initI18n();
        },
        initI18n() {
            if (!this.language) {
                this.setI18nType(this.i18nDefault);
                return;
            }
            this.setI18nType(this.language);
        },
        setI18nType(type) {
            this.i18nType = type;
            this.$i18n.locale =  type;
            let obj = this.i18nList.find(row => {
                return type == row.type;
            });
            if (obj) {
                this.i18nTitle = obj.name;
            }
            //储存当前语言
            uni.setStorage({key: "language", data: type})
        },
        //是否需要验证码
        getLoginConfig() {
            let self = this;
            LoginApi.getLoginConfig("1").then(resp => {
                self.passwordmode = resp.data.passwordmode;
                if(resp.data.sitettingJson){
                    let sitettingJson = JSON.parse(resp.data.sitettingJson.confs);
                    self.ignoreValidCode=sitettingJson.ignoreValidCode;
                }else{
                    self.ignoreValidCode = resp.data.ignoreValidCode;
                }
            })
        },
        //刷新验证码
        verification() {
            this.deviceId = uuid.uuid(16, 32);
            this.imgurl = '/api/api-uaa/validata/code/' + this.deviceId
        },
        change(obj) {
            this.i18nTitle = obj.name;
            this.$i18n.locale =  obj.type;
            uni.setStorage({key: "language", data: obj.type})
        },
        sm2Encrypt(password) {
            let pwd= sm2.doEncrypt(password, this.sw2PublicKey);
            return pwd.toString();
        },
        login: function () {
            if(this.loading){
                return;
            }
            if (!this.user.username || !this.user.password) {
                uni.showToast({
                    title: this.i18n('enterPwd', '输入账号密码！'), // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return;
            }
            let params = {
                password: this.user.password,
                username: this.user.username,
                deviceId: this.deviceId,
                tenantId:this.tenantId,
                loginType: loginTypeMap()[common.AppType]
            };
            //钉钉当有openId要绑定
            if (common.AppType == common.TypeDd && this.openId){
                params['openId'] = this.openId
            }
            if (this.ignoreValidCode != 'true') {
                params.validCode = this.user.validCode;
            }
            if ("md5" == this.passwordmode) {
                params.password =md5(this.user.password.trim())
            } else if ("sm2" == this.passwordmode) {
                params.password =this.sm2Encrypt(this.user.password.trim())
            }
            let self = this;
            this.loading = true;
            LoginApi.login(params).then(res => {
                this.loading = false;
                if (res.success) {
                    TokenUtil.setToken(res.data.accessToken.access_token);
                    self.currentUser();
                } else {
                    uni.showToast({
                        title: res.message, // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                }
            })
        },
        //获取当前用户信息
        async currentUser() {
            let self = this;
            await LoginApi.currentUser().then(res => {
                if (res.success) {
                    //储存用户信息
                    uni.setStorage({key: 'user', data: res.data})
                    uni.switchTab({
                        url: '/pages/RxWorkbench',
                        success: function(e) {
                            if (self.fromUrl) {
                                uni.navigateTo({
                                    url: JSON.parse(decodeURIComponent(self.fromUrl))
                                });
                            }
                        }
                    });
                }
            })
        },
    }
}
</script>

<style scoped>
.login-language-head {
    display: flex;
    align-items: center;
    cursor: pointer;
    height: 30px;
    color: #666666;
    font-size: 14px;
}

.login-language-common {
    min-width: 140px;
    background: #FFFFFF;
    box-shadow: 0px 0px 10px 1px rgba(0, 0, 0, 0.08);
    border-radius: 4px 4px 4px 4px;
    position: absolute;
    top: 4.5rem;
    left: 1rem;
    z-index: 9;
    padding: 10px 0px;
}

.login-language-common-list {
    height: 32px;
    align-items: center;
    display: flex;
    cursor: pointer;
    padding: 0px 5px;
    margin: 0px 5px;
    border-right: 2px;
}

.login-language-common-list:hover {
    background: rgba(24, 144, 255, 0.1);
}

.login-language-common-list-le {
    flex: 1;
    font-weight: 400;
    color: #29304C;
    font-size: 14px;
}

.LoginBox-common-input-longin {
    width: 13.4rem;
    height: 13.2rem;
    position: absolute;
    top: -8rem;
    right: -1.3rem;
}

.LoginBox-button-other i {
    font-size: 3rem;
    color: white;
}

.LoginBox-button-other i:nth-child(1) {
    margin-right: 3rem;
}

.LoginBox-button span:nth-child(1) {
    width: 3.16rem;
    height: 1px;
    background-image: linear-gradient(-90deg,
    #9bbdfd 0%,
    #9bbdfd 100%);
    opacity: 0.3;
}

.LoginBox-button span:nth-child(2) {
    color: #a1c2fd;
    font-size: .7rem;
    margin: 0px 0.5rem;
}

.LoginBox-button span:nth-child(3) {
    width: 3.16rem;
    height: 1px;
    background-image: linear-gradient(-90deg,
    #9bbdfd 0%,
    #9bbdfd 100%);
    opacity: 0.3;
}

.LoginBox-common {
    margin-top: 4rem;
}

.LoginBox-common-input {
    background-color: #ffffff;
    border-radius: 0.75rem;
    margin-top: 1.2rem;
    position: relative;
    padding: 3rem 1.5rem 4rem 1.5rem;
}

.LoginBox-common-input-longin {
    width: 13.4rem;
    height: 13.2rem;
    position: absolute;
    top: -8rem;
    right: -1.3rem;
}

.LoginBox-common-text {
    font-size: 1.3rem;
    line-height: 1.8rem;
    color: #ffffff;
}

.LoginBox-common-text span {
    display: block;
}

.imglist {
    width: 4rem;
    float: right;
}

.nalcik {
    width: 50% !important;
}

.netwlist input {
    margin: auto;
    margin-top: 2rem;
    border-radius: 1.25rem;
    border: 1px solid rgba(10, 27, 88, 0.1);
    width: 90%;
    padding-left: 0.5rem;
    height: 2.5rem;
    line-height: 2.5rem;
}

.netwlist button {
    margin: auto;
    width: 90%;
    background-image: linear-gradient(45deg, #007aff, #00c2ff);
    border-radius: 1.25rem;
    margin-top: 1rem;
    height: 2.5rem;
    line-height: 2.5rem;
    font-size: 14px;
    border: 0;
    color: #fff;
    margin-bottom: 1rem;
}

#LoginBox {
    width: 100%;
    height: 100%;
    padding: 1.5rem;
    overflow: hidden;
    background-color: white;
    background: linear-gradient(to bottom, #5e8dff, #2b67fc);
    background-size: cover;
    background-size: 100% auto;
    box-sizing: border-box;
}

.loginInDiv {
    width: 100%;
    overflow: hidden;
    height: 2.5rem;
    line-height: 2.5rem;
    padding-left: 1rem;
    padding-right: 1rem;
    border-radius: 1.5rem;
    background-color: #f5f5f5;
    box-sizing: border-box;
    margin-top: 1rem;
    display: flex;
    align-items: center;
}

.loginInDiv i {
    float: left;
    color: #5183ff;
    font-size: 1.2rem;
}

.loginInDiv input {
    height: 2.5rem;
    line-height: 2.5rem;
    margin-left: 0.5rem;
    border: none;
    flex: 1;
}

.btnLogin {
    width: 100%;
    height: 2.5rem;
    line-height: 2.5rem;
    border-radius: 1.5rem;
    box-sizing: border-box;
    color: white;
    margin-top: 1.5rem;
    background-image: linear-gradient(-90deg,
    #2b67fc 0%,
    #5e8dff 100%);
    box-shadow: 0px 0px 20px 0px rgba(212, 224, 255, 1);
}
</style>
